package com.segersten.othello.service.akka.lobby.dao;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import com.beust.jcommander.internal.Lists;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.segersten.othello.model.Color;
import com.segersten.othello.service.akka.Auth;
import com.segersten.othello.service.akka.Player;
import com.segersten.othello.service.akka.lobby.BoardReference;
import com.segersten.othello.service.akka.lobby.DomainPlayer;
import com.segersten.othello.service.akka.lobby.Game;

public class InMemoryLoginRegistry implements LoginRegistryDao
{
    private Map<DomainPlayer, Auth> registry = Maps.newHashMap();
    private Map<Auth, DomainPlayer> auths = Maps.newHashMap();
    private static Logger logger = Logger.getLogger(InMemoryLoginRegistry.class.getSimpleName());

    @Override
    public Auth addSession(String domain, String nick, Auth auth)
    {     
        DomainPlayer dp = new DomainPlayer(domain, nick);
        auths.put(auth, dp);
        Auth replaced = registry.put(dp, auth);
        if (replaced!=null && replaced.equals(auth)!=true) {
            auths.remove(replaced);
        }
        return replaced;
    }
    
    @Override
    public boolean isAuthorized(Auth auth)
    {
        return auths.keySet().contains(auth);
    }

    @Override
    public DomainPlayer getDomainPlayer(Auth auth)
    {
        return auths.get(auth);
    }

    @Override
    public Set<Auth> getAllSessions()
    {
        return new HashSet<Auth>(registry.values());
    }

    @Override
    public Player getPlayer(DomainPlayer domainPlayer)
    {
        Auth auth = registry.get(domainPlayer);
        if (auth==null) {
            throw new IllegalStateException("Session no found");
        }
        return new Player(domainPlayer.getNick(), auth);
    }
    
    /////////// Private //////////////
    
    private void assertNotNull(Object obj, String message)
    {
        if (obj==null) {
            throw new NullPointerException(message);
        }
    }

}
